<template>
  <div class="search-result-page">
    <div class="search-container">
      <!-- 搜索头部 -->
      <div class="search-header">
        <div class="search-info">
          <h2>搜索结果</h2>
          <span v-if="keyword" class="search-keyword">关键词：{{ keyword }}</span>
          <span class="search-count">共找到{{ total }}件商品</span>
        </div>

        <!-- 排序选项 -->
        <div class="sort-options">
          <span class="sort-label">排序：</span>
          <div class="sort-buttons">
            <el-button
                v-for="option in sortOptions"
                :key="option.value"
                :class="{ active: sortBy === option.value }"
                :type="sortBy === option.value ? 'primary' : ''"
                class="sort-btn"
                size="small"
                @click="handleSortChange(option.value)"
            >
              {{ option.label }}
            </el-button>
          </div>
          <!-- 移动端下拉选择器 -->
          <div class="mobile-sort-select">
            <el-select v-model="sortBy" placeholder="排序方式" @change="handleSortChange">
              <el-option
                  v-for="option in sortOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
              />
            </el-select>
          </div>
        </div>
      </div>

      <!-- 筛选条件 -->
      <div class="filter-section">
        <div class="filter-item">
          <span class="filter-label">价格区间：</span>
          <el-input
              v-model="minPrice"
              placeholder="最低价"
              style="width: 100px"
              type="number"
              @change="handleFilterChange"
          />
          <span style="margin: 0 10px">-</span>
          <el-input
              v-model="maxPrice"
              placeholder="最高价"
              style="width: 100px"
              type="number"
              @change="handleFilterChange"
          />
        </div>

        <div v-if="brands.length > 0" class="filter-item">
          <span class="filter-label">品牌：</span>
          <el-select v-model="selectedBrand" clearable placeholder="选择品牌" @change="handleFilterChange">
            <el-option
                v-for="brand in brands"
                :key="brand"
                :label="brand"
                :value="brand"
            />
          </el-select>
        </div>
      </div>

      <!-- 商品列表 -->
      <div v-loading="loading" class="products-section">
        <!-- 商品网格 -->
        <div v-if="!loading && products && products.length > 0" class="products-grid">
          <div
              v-for="product in products"
              :key="product.id"
              class="product-card"
              @click="goToProductDetail(product.id)"
          >
            <div class="product-image">
              <el-image
                  :alt="product.name"
                  :src="product.mainImage || '/placeholder.jpg'"
                  fit="cover"
              />
            </div>
            <div class="product-info">
              <h4 class="product-name">{{ product.name }}</h4>
              <p class="product-subtitle">{{ product.subtitle }}</p>
              <div class="product-price">
                <span class="current-price">¥{{ product.price }}</span>
                <span v-if="product.originalPrice" class="original-price">
                  ¥{{ product.originalPrice }}
                </span>
              </div>
              <div class="product-stats">
                <span class="sales">已售{{ product.sales }}件</span>
              </div>
            </div>
            <div class="product-actions">
              <el-button
                  :loading="addingToCart[product.id]"
                  size="small"
                  type="primary"
                  @click.stop="addToCart(product)"
              >
                加入购物车
              </el-button>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else-if="!loading && (!products || products.length === 0)" class="empty-result">
          <el-empty description="没有找到相关商品">
            <el-button type="primary" @click="goToHome">返回首页</el-button>
          </el-empty>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="total > 0" class="pagination">
        <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            background
            layout="prev, pager, next, jumper"
            @current-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref, watch} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {getProductList} from '@/api/product'
import {addToCart as addToCartApi} from '@/api/cart'
import {useCartStore, useUserStore} from '@/store'

// 路由相关
const route = useRoute()
const router = useRouter()

// 状态管理
const userStore = useUserStore()
const cartStore = useCartStore()

// 响应式数据
const loading = ref(false)
const products = ref([])
const brands = ref([])
const keyword = ref('')
const sortBy = ref('default')
const minPrice = ref('')
const maxPrice = ref('')
const selectedBrand = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const addingToCart = reactive({})

// 排序选项
const sortOptions = [
  {label: '综合排序', value: 'default'},
  {label: '价格↑', value: 'price_asc'},
  {label: '价格↓', value: 'price_desc'},
  {label: '销量↓', value: 'sales_desc'},
  {label: '最新', value: 'create_time_desc'}
]

// 初始化关键词
if (route.query.keyword) {
  keyword.value = route.query.keyword
}

// 获取排序字段
const getSortField = () => {
  const sortMap = {
    'price_asc': 'price',
    'price_desc': 'price',
    'sales_desc': 'sales',
    'create_time_desc': 'createTime'
  }
  return sortMap[sortBy.value] || 'id'
}

// 获取排序方向
const getSortOrder = () => {
  const orderMap = {
    'price_asc': 'asc',
    'price_desc': 'desc',
    'sales_desc': 'desc',
    'create_time_desc': 'desc'
  }
  return orderMap[sortBy.value] || 'desc'
}

// 获取商品列表
const fetchProducts = async () => {
  try {
    loading.value = true

    const params = {
      keyword: keyword.value,
      current: currentPage.value,
      size: pageSize.value,
      sortBy: getSortField(),
      sortOrder: getSortOrder(),
      minPrice: minPrice.value || undefined,
      maxPrice: maxPrice.value || undefined,
      brand: selectedBrand.value || undefined
    }

    console.log('搜索参数:', params)
    const response = await getProductList(params)
    console.log('搜索结果:', response)

    if (response && response.data) {
      products.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      products.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('搜索商品失败:', error)
    ElMessage.error(error.response?.data?.message || '搜索商品失败')
    products.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 监听路由变化
watch(() => route.query, (newQuery) => {
  keyword.value = newQuery.keyword || ''
  currentPage.value = 1
  fetchProducts()
}, {immediate: true})

// 页面初始化
onMounted(async () => {
  await fetchBrands()
})

// 获取品牌列表
const fetchBrands = async () => {
  try {
    // 暂时使用空数组，后续可以从商品列表中提取品牌
    brands.value = []
  } catch (error) {
    console.error('获取品牌列表失败:', error)
  }
}


// 排序变化
const handleSortChange = (value) => {
  if (value) {
    sortBy.value = value
  }
  currentPage.value = 1
  fetchProducts()
}

// 筛选变化
const handleFilterChange = () => {
  currentPage.value = 1
  fetchProducts()
}

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchProducts()
}

// 加入购物车
const addToCart = async (product) => {
  if (!userStore.isLoggedIn()) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    addingToCart[product.id] = true

    await addToCartApi({
      productId: product.id,
      quantity: 1
    })

    ElMessage.success('已加入购物车')
    await cartStore.fetchCartSummary()
  } catch (error) {
    console.error('加入购物车失败:', error)
    ElMessage.error('加入购物车失败')
  } finally {
    addingToCart[product.id] = false
  }
}

// 跳转到商品详情
const goToProductDetail = (productId) => {
  router.push(`/product/${productId}`)
}

// 返回首页
const goToHome = () => {
  router.push('/home')
}
</script>

<style scoped>
.search-result-page {
  min-height: 100vh;
  background: var(--bg-secondary);
  padding: 2rem 0;
}

.search-container {
  max-width: 1200px;
  margin: 0 auto;
  background: var(--bg-card);
  border-radius: var(--radius-2xl);
  overflow: hidden;
  box-shadow: var(--shadow-lg);
  border: 1px solid var(--border-light);
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem 2rem;
  border-bottom: 1px solid var(--border-light);
  background: var(--bg-secondary);
}

.search-info h2 {
  margin: 0 0 10px 0;
  font-size: 20px;
  color: #303133;
}

.search-keyword {
  color: #409eff;
  font-weight: 600;
  margin-right: 20px;
}

.search-count {
  color: #909399;
  font-size: 14px;
}

/* 排序选项样式 */
.sort-options {
  display: flex;
  align-items: center;
  gap: 15px;
}

.sort-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.sort-buttons {
  display: flex;
  gap: 8px;
}

.sort-btn {
  border-radius: var(--radius-xl);
  padding: 0.5rem 1rem;
  font-size: 0.875rem;
  font-weight: 500;
  transition: all 0.3s ease;
  border: 1px solid var(--border-medium);
  background: var(--bg-card);
  color: var(--text-secondary);
}

.sort-btn:hover {
  border-color: var(--primary-color);
  color: var(--primary-color);
  background: var(--primary-50);
}

.sort-btn.active {
  background: var(--gradient-primary);
  border-color: var(--primary-color);
  color: white;
  box-shadow: var(--shadow-sm);
}

.mobile-sort-select {
  display: none;
}

.filter-section {
  display: flex;
  align-items: center;
  gap: 2rem;
  padding: 1.5rem 2rem;
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border-light);
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-label {
  color: #606266;
  font-weight: 500;
  white-space: nowrap;
}

.products-section {
  padding: 30px;
  min-height: 400px;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 1.5rem;
}

.product-card {
  border: 1px solid var(--border-light);
  border-radius: var(--radius-2xl);
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  background: var(--bg-card);
  box-shadow: var(--shadow-sm);
  position: relative;
}

.product-card:hover {
  border-color: var(--primary-color);
  box-shadow: var(--shadow-xl);
  transform: translateY(-4px);
}

.product-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: var(--gradient-primary);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.product-card:hover::before {
  opacity: 1;
}

.product-image {
  width: 100%;
  height: 200px;
}

.product-image .el-image {
  width: 100%;
  height: 100%;
}

.product-info {
  padding: 15px;
}

.product-name {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #303133;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-subtitle {
  margin: 0 0 10px 0;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-price {
  margin-bottom: 8px;
}

.current-price {
  color: #f56c6c;
  font-size: 16px;
  font-weight: 600;
}

.original-price {
  color: #c0c4cc;
  font-size: 12px;
  text-decoration: line-through;
  margin-left: 8px;
}

.product-stats {
  font-size: 12px;
  color: #909399;
}

.product-actions {
  padding: 0 15px 15px;
}

.product-actions .el-button {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-result-page {
    padding: 1rem 0;
  }

  .search-container {
    margin: 0 1rem;
  }

  .search-header {
    flex-direction: column;
    gap: 1rem;
    padding: 1rem 1.5rem;
    align-items: flex-start;
    padding: 15px 20px;
  }

  .search-info h2 {
    font-size: 18px;
    margin-bottom: 8px;
  }

  .search-info p {
    font-size: 13px;
  }

  .sort-options {
    width: 100%;
    justify-content: space-between;
  }

  .sort-buttons {
    display: none;
  }

  .mobile-sort-select {
    display: block;
    flex: 1;
  }

  .mobile-sort-select .el-select {
    width: 100%;
  }

  .filter-section {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
    padding: 1rem 1.5rem;
  }

  .filter-item {
    width: 100%;
    flex-wrap: wrap;
  }

  .filter-item .el-select,
  .filter-item .el-input {
    flex: 1;
    min-width: 120px;
  }

  .products-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 1rem;
    padding: 1rem;
    gap: 10px;
    padding: 10px 20px;
  }

  .product-card {
    border-radius: 8px;
  }

  .product-image {
    height: 120px;
  }

  .product-info {
    padding: 8px;
  }

  .product-name {
    font-size: 13px;
    line-height: 1.3;
  }

  .current-price {
    font-size: 14px;
  }

  .product-actions {
    padding: 0 8px 8px;
  }

  .pagination {
    padding: 15px 20px;
  }
}

@media (max-width: 480px) {
  .search-container {
    margin: 10px;
    border-radius: 8px;
  }

  .search-header {
    padding: 12px 15px;
  }

  .filter-section {
    padding: 12px 15px;
  }

  .products-grid {
    padding: 8px 15px;
    gap: 8px;
  }

  .product-image {
    height: 100px;
  }

  .product-name {
    font-size: 12px;
  }

  .current-price {
    font-size: 13px;
  }
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 30px;
  background: white;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-container {
    margin: 0 10px;
  }

  .search-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
    padding: 15px 20px;
  }

  .filter-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
    padding: 15px 20px;
  }

  .products-section {
    padding: 20px;
  }

  .products-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 15px;
  }

  .pagination {
    padding: 20px;
  }
}
</style>
